package com.cp.rabbitmq.simplequeue;

import com.cp.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Coder编程
 * @version V1.0
 * @Title: ConsumerOne
 * @Package: com.cp.rabbitmq.simplequeue
 * @Description: 接受消息
 * @date 2019/7/9  21:46
 **/

public class Consumer {

    private static final String QUEUE_NAME = "TEST_SIMPLE_QUEUE";

    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws IOException,
            TimeoutException, ShutdownSignalException,
            ConsumerCancelledException, InterruptedException {

        // 获取连接
        Connection connection = ConnectionUtils.getConnection();
        // 创建频道
        Channel channel = connection.createChannel();

        //队列声明
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //定义消费者
        DefaultConsumer consumer = new DefaultConsumer(channel){
            //获取到达消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {

                String msg=new String(body,"utf-8");
                System.out.println("new api recv:"+msg);
            }
        };

        //监听队列
        channel.basicConsume(QUEUE_NAME, true,consumer);
    }

    private static void oldapiu() throws IOException, TimeoutException,
            InterruptedException {
        // 获取连接
        Connection connection = ConnectionUtils.getConnection();

        // 创建频道
        Channel channel = connection.createChannel();
        // 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列
        channel.basicConsume(QUEUE_NAME, true, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msgString = new String(delivery.getBody());
            System.out.println("[recv] msg:" + msgString);
        }
    }
}
